using MediatR;
using Microsoft.EntityFrameworkCore;
using Medical.Domain;
using Medical.ErrorCode;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	public class GetDepartmentsListQueryHandler : IRequestHandler<GetDepartmentsListQuery, ApiPaging<DepartmentDto>>
	{
		private readonly IBaseRepository<Department> _repository;

		public GetDepartmentsListQueryHandler(IBaseRepository<Department> repository)
		{
			_repository = repository;
		}

		public async Task<ApiPaging<DepartmentDto>> Handle(GetDepartmentsListQuery request, CancellationToken cancellationToken)
		{
			var query = _repository.GetAll().Where(x => !x.IsDeleted);
			if (!string.IsNullOrEmpty(request.NameKeyword)) query = query.Where(x => x.Name.Contains(request.NameKeyword));
			if (request.IsKeyDepartment.HasValue) query = query.Where(x => x.IsKeyDepartment == request.IsKeyDepartment.Value);
			if (request.IsEmergencyAvailable.HasValue) query = query.Where(x => x.IsEmergencyAvailable == request.IsEmergencyAvailable.Value);

			var totalCount = await query.CountAsync(cancellationToken);
			var items = await query
				.OrderBy(x => x.Name)
				.Skip((request.Page - 1) * request.Size)
				.Take(request.Size)
				.Select(x => new DepartmentDto
				{
					DepartmentId = x.DepartmentId,
					Name = x.Name,
					Address = x.Address,
					RegistrationFee = x.RegistrationFee,
					ParentDepartmentId = x.ParentDepartmentId,
					IsKeyDepartment = x.IsKeyDepartment,
					IsEmergencyAvailable = x.IsEmergencyAvailable,
					BedCount = x.BedCount,
					CreatedAt = x.CreatedAt,
					UpdatedAt = x.UpdatedAt
				})
				.ToListAsync(cancellationToken);

			var totalPage = (int)Math.Ceiling(totalCount / (double)request.Size);
			return new ApiPaging<DepartmentDto> { totalCount = totalCount, totalPage = totalPage, data = items };
		}
	}
}
